package com.yupi.springbootinit.manager;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.jayway.jsonpath.JsonPath;
import com.yupi.springbootinit.model.dto.ai.AiChatRequest;
import com.yupi.springbootinit.model.dto.ai.AiSendRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * AI 服务请求操作
 */
@Component
@Slf4j
public class AiManager {
    private static AiSendRequest aiSendRequest;

    @Resource
    public void setAiSendRequest(AiSendRequest aiSendRequest) {
        AiManager.aiSendRequest = aiSendRequest;
    }

    public static AiChatRequest sendAiPost(String biCode, String question) {
        String linkUrl = aiSendRequest.getLinkUrl();
        String biApiKey = aiSendRequest.getBiApiKey();
        String codeAndKey = biApiKey.replace("{}", biCode);

        JSONObject requestBody = new JSONObject();
        requestBody.set("app_code", biCode);
        JSONArray messages = new JSONArray();
        JSONObject message = new JSONObject();
        message.set("role", "user");
        message.set("content", question);
        messages.add(message);
        requestBody.set("messages", messages);

        System.out.println(requestBody);
        HttpResponse execute;
        try {
            execute = HttpUtil.createPost(linkUrl)
                    .header("Authorization", "Bearer " + codeAndKey)
                    .header("Content-Type", "application/json")
                    .body(requestBody.toString())
                    .execute();
        } catch (Exception e) {
            log.error("AI 发送请求失败");
            throw new RuntimeException(e.getMessage());
        }

        String bodied = execute.body();
        log.info(bodied);

        List<String> contents = JsonPath.read(bodied, "$..content");
        String content = contents.get(0);
        List<Integer> totalTokens = JsonPath.read(bodied, "$..total_tokens");
        Integer totalToken = totalTokens.get(0);

        AiChatRequest chatRequest = new AiChatRequest();
        chatRequest.setContent(content);
        chatRequest.setTotalToken(totalToken);
        return chatRequest;
    }
}
